{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "CdL1ZvDepO-X"
   },
   "source": [
    "<a href=\"https://colab.research.google.com/github/jeffheaton/app_generative_ai/blob/main/assignments/assignment_yourname_class6.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "R_pemiL8pO-Y"
   },
   "source": [
    "# T81-559: Applications of Generative AI\n",
    "* Instructor: [Jeff Heaton](https://sites.wustl.edu/jeffheaton/), McKelvey School of Engineering, [Washington University in St. Louis](https://engineering.wustl.edu/index.html)\n",
    "* For more information visit the [class website](https://sites.wustl.edu/jeffheaton/t81-559/).\n",
    "\n",
    "**Module 6 Assignment: RAG**\n",
    "\n",
    "**Student Name: Your Name**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "lky4xopspO-Z"
   },
   "source": [
    "# Assignment Instructions\n",
    "\n",
    "Use RAG to have the LLM read and analyze the story [\"Clockwork Dreams and Brass Shadows\"](https://data.heatonresearch.com/data/t81-559/assignments/clockwork.pdf). The story can be found at the following URL.\n",
    "\n",
    "* https://data.heatonresearch.com/data/t81-559/assignments/clockwork.pdf\n",
    "\n",
    "Answer the following questions.\n",
    "\n",
    "1. What is the invention that could change everything?\n",
    "2. What is Eliza Hawthorne's job title?\n",
    "3. Who orchestrating the conspiracy?\n",
    "4. Does Victor have a last name? (yes or no)\n",
    "5. What city does the story take place in?\n",
    "6. What is Jasper Thorne's job title?\n",
    "\n",
    "These answers should be as simple as possible, yes/no, a city name, or a simple job title like \"software engineer\". Product a table that might look like the following. Note that these are **NOT** the correct answers. Submit all answers in lower case. Your answers must match the solution exactly.\n",
    "\n",
    "| Question   | Answer                          |\n",
    "|------------|---------------------------------|\n",
    "| 1.         | computer                        |\n",
    "| 2.         | software engineer               |\n",
    "| 3.         | sebastian                       |\n",
    "| 4.         | yes                             |\n",
    "| 5.         | cincinnati                      |\n",
    "| 6.         | police officer                  |\n",
    "|------------|---------------------------------|\n",
    "\n",
    "Submit a dataframe with answers to the the questions above, in this format.\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "U4LQZW_SpO-Z"
   },
   "source": [
    "# Google CoLab Instructions\n",
    "\n",
    "If you are using Google CoLab, it will be necessary to mount your GDrive so that you can send your notebook during the submit process. Running the following code will map your GDrive to ```/content/drive```."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "1ZnCEIEopO-Z"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "try:\n",
    "    from google.colab import drive, userdata\n",
    "    drive.mount('/content/drive', force_remount=True)\n",
    "    COLAB = True\n",
    "    print(\"Note: using Google CoLab\")\n",
    "except:\n",
    "    print(\"Note: not using Google CoLab\")\n",
    "    COLAB = False\n",
    "\n",
    "# OpenAI Secrets\n",
    "if COLAB:\n",
    "    os.environ[\"OPENAI_API_KEY\"] = userdata.get('OPENAI_API_KEY')\n",
    "\n",
    "# Install needed libraries in CoLab\n",
    "if COLAB:\n",
    "    !pip install langchain langchain_openai langchain_community pypdf pdfkit sentence-transformers chromadb\n",
    "    !apt-get install wkhtmltopdf"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "id": "PMLHwV0hpO-a"
   },
   "source": [
    "# Assignment Submit Function\n",
    "\n",
    "You will submit the 10 programming assignments electronically.  The following submit function can be used to do this.  My server will perform a basic check of each assignment and let you know if it sees any basic problems.\n",
    "\n",
    "**It is unlikely that should need to modify this function.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "ozSyLCNtpO-a"
   },
   "outputs": [],
   "source": [
    "import base64\n",
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import requests\n",
    "import PIL\n",
    "import PIL.Image\n",
    "import io\n",
    "from io import BytesIO\n",
    "\n",
    "# This function submits an assignment.  You can submit an assignment as much as you like, only the final\n",
    "# submission counts.  The paramaters are as follows:\n",
    "# data - List of pandas dataframes or images.\n",
    "# key - Your student key that was emailed to you.\n",
    "# course - The course that you are in, currently t81-558 or t81-559.\n",
    "# no - The assignment class number, should be 1 through 1.\n",
    "# source_file - The full path to your Python or IPYNB file.  This must have \"_class1\" as part of its name.\n",
    "# .             The number must match your assignment number.  For example \"_class2\" for class assignment #2.\n",
    "def submit(data,key,course,no,source_file=None):\n",
    "    if source_file is None and '__file__' not in globals(): raise Exception('Must specify a filename when a Jupyter notebook.')\n",
    "    if source_file is None: source_file = __file__\n",
    "    suffix = '_class{}'.format(no)\n",
    "    if suffix not in source_file: raise Exception('{} must be part of the filename.'.format(suffix))\n",
    "    with open(source_file, \"rb\") as image_file:\n",
    "        encoded_python = base64.b64encode(image_file.read()).decode('ascii')\n",
    "    ext = os.path.splitext(source_file)[-1].lower()\n",
    "    if ext not in ['.ipynb','.py']: raise Exception(\"Source file is {} must be .py or .ipynb\".format(ext))\n",
    "    payload = []\n",
    "    for item in data:\n",
    "        if type(item) is PIL.Image.Image:\n",
    "            buffered = BytesIO()\n",
    "            item.save(buffered, format=\"PNG\")\n",
    "            payload.append({'PNG':base64.b64encode(buffered.getvalue()).decode('ascii')})\n",
    "        elif type(item) is pd.core.frame.DataFrame:\n",
    "            payload.append({'CSV':base64.b64encode(item.to_csv(index=False).encode('ascii')).decode(\"ascii\")})\n",
    "    r= requests.post(\"https://api.heatonresearch.com/wu/submit\",\n",
    "        headers={'x-api-key':key}, json={ 'payload': payload,'assignment': no, 'course':course, 'ext':ext, 'py':encoded_python})\n",
    "    if r.status_code==200:\n",
    "        print(\"Success: {}\".format(r.text))\n",
    "    else: print(\"Failure: {}\".format(r.text))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "id": "H7kgvLHspO-a",
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "source": [
    "# Assignment #6 Sample Code\n",
    "\n",
    "The following code provides a starting point for this assignment."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "8ZPLGWgkpO-a"
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import pandas as pd\n",
    "from scipy.stats import zscore\n",
    "import string\n",
    "\n",
    "\n",
    "# This is your student key that I emailed to you at the beginnning of the semester.\n",
    "key = \"uTtH5yNbPs9tjdjdsBf9V9FaQA9RU2iP5cL7F3zH\"\n",
    "\n",
    "# You must also identify your source file.  (modify for your local setup)\n",
    "file='/content/drive/MyDrive/Colab Notebooks/assignment_yourname_class6.ipynb'  # Google CoLab\n",
    "# file='C:\\\\Users\\\\jeffh\\\\projects\\\\t81_558_deep_learning\\\\assignments\\\\assignment_yourname_class5.ipynb'  # Windows\n",
    "# file='/Users/jheaton/projects/t81_558_deep_learning/assignments/assignment_yourname_class5.ipynb'  # Mac/Linux\n",
    "\n",
    "# Begin assignment"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "id": "VHToGP6gKWhS"
   },
   "outputs": [],
   "source": [
    "# Note, this data is wrong, its just an example of the format.\n",
    "data = {\n",
    "    'question': [1, 2, 3, 4, 5, 6],\n",
    "    'answer': ['computer', 'software engineer', 'sebastian', 'yes', 'cincinnati', 'police officer']\n",
    "}\n",
    "df_submit = pd.DataFrame(data)\n",
    "\n",
    "# Submit\n",
    "submit(source_file=file,data=[df_submit],course='t81-559',key=key,no=6)"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "colab": {
   "provenance": []
  },
  "kernelspec": {
   "display_name": "Python 3.11 (torch)",
   "language": "python",
   "name": "pytorch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
